/**
 * 
 */
package com.maszy.commons.tools;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;

import com.maszy.bean.Dept;
import com.maszy.bean.DoorStore;
import com.maszy.bean.GoodPlan;
import com.maszy.bean.Product;
import com.maszy.service.DeptService;
import com.maszy.service.DoorStoreService;
import com.maszy.service.GoodPlanService;
import com.maszy.service.ProductService;

/**
 * @作者 Allen Shu
 * @创建日期 2012-6-19
 * @版本 V 1.0
 */

public class PrintGoodPlanReport1 implements Printable {
//	private int PAGES = 0;
	/*
	 * Graphic指明打印的图形环境；PageFormat指明打印页格式（页面大小以点为计量单位，
	 * 1点为1英寸的1/72，1英寸为25.4毫米。A4纸大致为595×842点）；page指明页号
	 */
	private final int _titleFontSize = 14;
	private final int _contentFontSize = 12;
	private final int _x = 20;
	private final int _x2 = 300;
	private final int _y = 20;
	private final int stepy = 10;
	String goodType = "";
	private GoodPlan goodplan;
	private String deptName="0";
	// 打印内容到指定位置
	public void printContent(String printName) {
		System.out.println("PrintReady:"+"\t"+printName);
//		printName = "Canon MP250";
//		PAGES = 1; // 获取打印总页数
		// 指定打印输出格式
		DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
		DocAttributeSet das = new HashDocAttributeSet();
		// 定位默认的打印服务
		// PrintService printService =
		// PrintServiceLookup.lookupDefaultPrintService();
		/*
		 * if("1".equals(goodplan.getGoodPlan_Type())){ printName="2lou"; }
		 * if("2".equals(goodplan.getGoodPlan_Type())){ printName="4lou"; }
		 */

		// printName=goodplan.getPrint_name();
		PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
				flavor, das);
		for (int i = 0; i < printServices.length; i++) {
//			 System.out.println("第"+(i+1)+"个打印机:"+printServices[i].getName()+"  printName:"+printName);
			if (printName.equals(printServices[i].getName())) {
				// 创建打印作业
				DocPrintJob job = printServices[i].createPrintJob();
				// 设置打印属性
				PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
				// 设置纸张大小,也可以新建MediaSize类来自定义大小
				pras.add(MediaSizeName.ISO_A4);

				// 指定打印内容
				Doc doc = new SimpleDoc(this, flavor, das);
				// 不显示打印对话框，直接进行打印工作
				try {
					job.print(doc, pras); // 进行每一页的具体打印操作
				} catch (PrintException pe) {
					pe.printStackTrace();
				}
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.awt.print.Printable#print(java.awt.Graphics,
	 * java.awt.print.PageFormat, int)
	 */
	public int print(Graphics gp, PageFormat pf, int page)
			throws PrinterException {
		// TODO Auto-generated method stub
		Graphics2D g2 = (Graphics2D) gp;
		g2.setPaint(Color.black); // 设置打印颜色为黑色
		g2.translate(pf.getImageableX(), pf.getImageableY());// 转换坐标，确定打印边界
		int i=queryGoodPlanReportByDept(g2,20,50);
		if(i==0){
			return Printable.NO_SUCH_PAGE;
		}else{
			return PAGE_EXISTS;
		}
	}

	public int queryGoodPlanReportByDept(Graphics2D g2, int x, int y) {
		int i=0;
		GoodPlan obj = new GoodPlan();
		String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar
				.getInstance().getTime());
		obj.setGoodPlan_BeginDate(date + " 00:00:00");
		obj.setGoodPlan_EndDate(date + " 23:59:59");
//		 obj.setGoodPlan_BeginDate("2012-06-14"+" 00:00:00");
//		 obj.setGoodPlan_EndDate("2012-06-14"+" 23:59:59");
		obj.setGoodPlan_Type("1");
		// 先获取所有门店的信息
		DoorStoreService doorStoreService = new DoorStoreService();
		List<DoorStore> doorStoreList = doorStoreService.queryAll();
		// 获取所有产品信息
		ProductService productService = new ProductService();
		List<Product> productList = productService.queryAll();
		// 查询当日所有门店的原材料供应单的报表情况.
		GoodPlanService goodPlanService = new GoodPlanService();
		List<GoodPlan> goodPlanList = goodPlanService.queryOneDayGoodPlan1(obj);
		if(goodPlanList!=null){
			if(goodPlanList.size()>0){
				g2.setFont(new Font("宋体", Font.PLAIN, _titleFontSize));
				g2.drawString("原材料供应单" + "----" + deptName+"    "+new SimpleDateFormat("yyyy-MM-dd").format(Calendar
						.getInstance().getTime()), _x + 150, _y); // 具体打印每一行文本，同时走纸移位
				g2.setFont(new Font("宋体", Font.PLAIN, _contentFontSize));
				//按部门循环
				i=PrintReport(g2,x,y ,doorStoreList,productList,goodPlanList);
			}
		}
		return i;
	}
	public int PrintReport(Graphics2D g2, int x, int y,List<DoorStore> doorStoreList,List<Product> productList,List<GoodPlan> goodPlanList){
		int pagesize=0;
		List<List<Object>> list = new ArrayList<List<Object>>();
		g2.drawString("品名",x,y-5);
		int tX=x+60;
		g2.drawString("规格",tX,y-5);
		tX+=60;
		for(int z=1;z<doorStoreList.size();z++){
			g2.drawString(doorStoreList.get(z).getDoorStore_Name().substring(0,2),tX,y-5);
			tX+=35;
			if(z==doorStoreList.size()-1){
				g2.drawString("合计",tX,y-5);
			}
		}
		// 先循环出所有单品
		for (int i = 0; i < productList.size(); i++) {
			if (productList.get(i).getProduct_Dept_Name().equals(deptName)) {
				String printStr="";
				List<Object> reportItemList = new ArrayList<Object>();
			//	reportItemList.add("<td>"+productList.get(i).getProduct_Name() + "</td>");
				printStr=productList.get(i).getProduct_Name()+"|"+productList.get(i).getProduct_Specification()+"|";
				int sum = 0;
				LabelA:
				// 循环出所有门店
				for (int j = 1; j < doorStoreList.size(); j++) {
					boolean b = false;
					LabelB:
					// 循环所有要货计划表头
					for (int m = 0; m < goodPlanList.size(); m++) {
						// 判断要货计划里是否有该门店
						if (goodPlanList.get(m).getDoorStore_Id()
								.equals(doorStoreList.get(j).getDoorStore_Id())) {
							// 如果有该门店.循环这家门店要货计划明细数据
							List<Product> planBodyList = goodPlanList.get(m)
									.getProductList();
							LabelC: for (int o = 0; o < planBodyList.size(); o++) {
								// 如果要货明细里和单品对应上,则把数量加进去,否则显示0
								if (productList.get(i).getProduct_Id().equals(planBodyList.get(o).getProduct_Id())) {
									printStr+=planBodyList.get(o).getProduct_Quantity()+"|";
									// reportItemList.add("<td>"+Integer.parseInt(planBodyList.get(o).getProduct_Quantity())+"</td>");
									// g2.drawString(planBodyList.get(o).getProduct_Quantity(),
									// x+_x, 120);
									sum += Integer.parseInt(planBodyList.get(o)
											.getProduct_Quantity());
									b = true;
									
									break LabelB;
								}
							}
						}
					}
					if(b==false){
							printStr+=0+"|";
					}
				}
				// for(Object str:reportItemList){
				// if(!"".equals(str)){
				// System.out.println(str);
				// }
				// }
				printStr+=sum;
				if(sum>0){
					y=y+stepy;
					int tempX=x;
					String[] print_arr=printStr.split("[|]");
					for(int q=0;q<print_arr.length;q++){
						if(q==1){
							tempX=tempX+25;
						}if(q==2){
							tempX=tempX+30;
						}
						g2.drawString(print_arr[q], tempX, y);
						tempX=tempX+35;
					}
					y=y+5;
					g2.setFont(new Font("宋体", Font.PLAIN, 6));
					if(i%2==0){
						g2.drawString("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------", _x, y);
					}else{
						g2.drawLine(_x, y, 530, y);
					}
					y=y+5;
					if(y>500){
						return 1;
					}
					g2.setFont(new Font("宋体", Font.PLAIN, 12));
				}
				list.add(reportItemList);
			}
		}
		return pagesize;
	}
	public void PrintReady(){
		DeptService deptService=new DeptService();
		List<Dept> deptList=deptService.queryAllAndCountProduct();
		for(int q=0;q<1;q++){
			if(deptList.get(q).getCountProduct()>0){
				this.deptName=deptList.get(q).getDept_name();
				printContent(deptList.get(q).getPrint_name());
			}
			
		}		
		System.out.println("PrintReady:"+"\t"+deptName);
	}
	public static void main(String args[]) throws FileNotFoundException,
			MalformedURLException {
		PrintGoodPlanReport1 ptool = new PrintGoodPlanReport1();
		ptool.PrintReady();
	}
}
